package com.budwk.app.miniapp.services.impl;

import com.budwk.app.miniapp.models.WxVolunteerSMPassCheck;
import com.budwk.starter.database.service.BaseServiceImpl;
import com.budwk.app.miniapp.models.WxVolunteer;
import com.budwk.app.miniapp.services.WxvolunteerService;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.loader.annotation.IocBean;

@IocBean(args = {"refer:dao"})
public class WxvolunteerServiceImpl extends BaseServiceImpl<WxVolunteer> implements WxvolunteerService {
    public WxvolunteerServiceImpl(Dao dao) {
        super(dao);
    }

    /*
     * 获取订阅消息次数
     * */
    @Override
    public Integer getSMPassCheckCount(String openId) {
        Sql sql = Sqls.create("select pushtimes from wx_volunteer where openid = @openId");
        sql.setParam("openId", openId);
        sql.setCallback(Sqls.callback.integer());
        dao().execute(sql);
        return sql.getInt();
    }

    /*
     * 统计事件数量
     * */
    @Override
    public Integer getHomePageEventStatistic() {
        Sql sql = Sqls.create("select count(1) from wx_event where ( event_type = 'natural_disaster' or event_type = 'emergency_events') and event_status != 'canceled'");
        sql.setCallback(Sqls.callback.integer());
        dao().execute(sql);
        return sql.getInt();
    }

    @Override
    public Integer addSMPassCheck(WxVolunteerSMPassCheck bo) {
        Cnd cnd = Cnd.NEW();
        cnd.and("openid", "=", bo.getOpenId());
        WxVolunteer wxVolunteer = fetch(cnd);
        if (wxVolunteer == null) {
            return 0;
        }
        Integer pushTimes = wxVolunteer.getPushtimes();
        if (pushTimes == null) pushTimes = 0;
        int newPushTime;
        if (bo.getStatus() == 1) {
            newPushTime = pushTimes + bo.getTimes();   // 如果是同意则添加微信推送的通行证的数量
        } else {
            newPushTime = 0;   // 如果用户是拒绝则清零
        }
        newPushTime = Math.max(newPushTime, 0);  // 保证消息发送次数最少为0
        wxVolunteer.setPushtimes(newPushTime);
        update(wxVolunteer);
        return newPushTime;
    }
}
